package com.lcz.manage.util;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

/**
 * @author lucz@yunrong.cn
 * @version V3.0
 * @date 2021/9/24 9:23
 */
public class ThreadLocalUtils {

    private static final Logger LOG = LoggerFactory.getLogger(ThreadLocalUtils.class);

    private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal<>();

    private static final ThreadLocalUtils INSTANCE = new ThreadLocalUtils();

    public static ThreadLocalUtils getInstance() {
        return INSTANCE;
    }

    private ThreadLocalUtils() {
    }

    /**
     * 线程上下文放置变量
     *
     * @param key key
     * @param object 变量
     */
    public void putObject(String key, Object object) {
        getMap().put(key, object);
    }

    /**
     * 线程上下文获取变量
     *
     * @param key key
     * @return 变量
     */
    public Object getObject(String key) {
        return getMap().get(key);
    }

    /**
     * 线程上下文清理
     */
    public void remove() {
        THREAD_LOCAL.remove();
    }

    private Map<String, Object> getMap() {
        Map<String, Object> threadLocalMap = THREAD_LOCAL.get();
        if (threadLocalMap == null) {
            threadLocalMap = Maps.newHashMap();
            THREAD_LOCAL.set(threadLocalMap);
        }
        return threadLocalMap;
    }

}
